<template>
  <div class="enrollments-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="学号">
          <el-input
            v-model="searchForm.sno"
            placeholder="请输入学号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="课程号">
          <el-input
            v-model="searchForm.cno"
            placeholder="请输入课程号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="成绩状态">
          <el-select
            v-model="searchForm.gradeStatus"
            placeholder="请选择成绩状态"
            clearable
            style="width: 150px"
          >
            <el-option label="已录入" value="recorded" />
            <el-option label="未录入" value="unrecorded" />
            <el-option label="及格" value="pass" />
            <el-option label="不及格" value="fail" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleEnroll">
            <el-icon><Plus /></el-icon>
            学生选课
          </el-button>
          <el-button type="warning" @click="handleBatchGrade">
            <el-icon><Edit /></el-icon>
            批量录入成绩
          </el-button>
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出Excel
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sno" label="学号" width="120" />
        <el-table-column prop="sname" label="学生姓名" width="120" />
        <el-table-column prop="cno" label="课程号" width="120" />
        <el-table-column prop="cname" label="课程名" width="200" />
        <el-table-column prop="teacher" label="教师" width="120" />
        <el-table-column prop="grade" label="成绩" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.grade === null || row.grade === undefined" type="info">
              未录入
            </el-tag>
            <el-tag v-else-if="row.grade >= 60" type="success">
              {{ row.grade }}
            </el-tag>
            <el-tag v-else type="danger">
              {{ row.grade }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleGrade(row)"
            >
              <el-icon><Edit /></el-icon>
              录入成绩
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDrop(row)"
            >
              <el-icon><Delete /></el-icon>
              退课
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 选课对话框 -->
    <el-dialog
      title="学生选课"
      v-model="enrollDialogVisible"
      width="500px"
      @close="handleEnrollDialogClose"
    >
      <el-form
        ref="enrollFormRef"
        :model="enrollForm"
        :rules="enrollRules"
        label-width="80px"
      >
        <el-form-item label="学号" prop="sno">
          <el-select
            v-model="enrollForm.sno"
            placeholder="请选择学生"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="student in students"
              :key="student.sno"
              :label="`${student.sno} - ${student.sname}`"
              :value="student.sno"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="cno">
          <el-select
            v-model="enrollForm.cno"
            placeholder="请选择课程"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="course in courses"
              :key="course.cno"
              :label="`${course.cno} - ${course.cname}`"
              :value="course.cno"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="enrollDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEnrollSubmit" :loading="enrollLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 录入成绩对话框 -->
    <el-dialog
      title="录入成绩"
      v-model="gradeDialogVisible"
      width="400px"
      @close="handleGradeDialogClose"
    >
      <el-form
        ref="gradeFormRef"
        :model="gradeForm"
        :rules="gradeRules"
        label-width="80px"
      >
        <el-form-item label="学生">
          <el-input :value="`${gradeForm.sno} - ${gradeForm.sname}`" disabled />
        </el-form-item>
        <el-form-item label="课程">
          <el-input :value="`${gradeForm.cno} - ${gradeForm.cname}`" disabled />
        </el-form-item>
        <el-form-item label="成绩" prop="grade">
          <el-input-number
            v-model="gradeForm.grade"
            :min="0"
            :max="100"
            placeholder="请输入成绩"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="gradeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleGradeSubmit" :loading="gradeLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量录入成绩对话框 -->
    <el-dialog
      title="批量录入成绩"
      v-model="batchGradeDialogVisible"
      width="600px"
    >
      <div v-if="selectedRows.length === 0" class="no-selection">
        <el-empty description="请先选择要录入成绩的选课记录" />
      </div>
      <div v-else>
        <p>已选择 {{ selectedRows.length }} 条记录</p>
        <el-table :data="selectedRows" style="width: 100%" max-height="300">
          <el-table-column prop="sno" label="学号" width="100" />
          <el-table-column prop="sname" label="学生" width="100" />
          <el-table-column prop="cname" label="课程" />
          <el-table-column label="成绩" width="120">
            <template #default="{ row, $index }">
              <el-input-number
                v-model="batchGrades[$index]"
                :min="0"
                :max="100"
                size="small"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchGradeDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleBatchGradeSubmit" 
            :loading="batchGradeLoading"
            :disabled="selectedRows.length === 0"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download } from '@element-plus/icons-vue'
import { enrollmentApi, studentApi, courseApi } from '@/api'
import * as XLSX from 'xlsx'

export default {
  name: 'Enrollments',
  components: {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Download
  },
  setup() {
    const loading = ref(false)
    const enrollLoading = ref(false)
    const gradeLoading = ref(false)
    const batchGradeLoading = ref(false)
    const enrollDialogVisible = ref(false)
    const gradeDialogVisible = ref(false)
    const batchGradeDialogVisible = ref(false)
    const enrollFormRef = ref()
    const gradeFormRef = ref()
    
    const searchForm = reactive({
      sno: '',
      cno: '',
      gradeStatus: ''
    })
    
    const enrollForm = reactive({
      sno: '',
      cno: ''
    })
    
    const gradeForm = reactive({
      sno: '',
      sname: '',
      cno: '',
      cname: '',
      grade: null
    })
    
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const students = ref([])
    const courses = ref([])
    const selectedRows = ref([])
    const batchGrades = ref([])
    
    const enrollRules = {
      sno: [
        { required: true, message: '请选择学生', trigger: 'change' }
      ],
      cno: [
        { required: true, message: '请选择课程', trigger: 'change' }
      ]
    }
    
    const gradeRules = {
      grade: [
        { required: true, message: '请输入成绩', trigger: 'blur' },
        { type: 'number', min: 0, max: 100, message: '成绩应在0-100之间', trigger: 'blur' }
      ]
    }
    
    // 加载选课数据
    const loadData = async () => {
      loading.value = true
      try {
        // 构建筛选参数，只传递有值的参数
        const params = {}
        if (searchForm.sno && searchForm.sno.trim()) {
          params.sno = searchForm.sno.trim()
        }
        if (searchForm.cno && searchForm.cno.trim()) {
          params.cno = searchForm.cno.trim()
        }
        if (searchForm.gradeStatus) {
          params.gradeStatus = searchForm.gradeStatus
        }
        
        console.log('前端发送筛选参数:', params)
        const response = await enrollmentApi.getEnrollments(params)
        console.log('前端接收到的完整响应:', response)
        
        if (response.code === 200) {
          console.log('响应数据类型:', typeof response.data)
          console.log('响应数据内容:', response.data)
          
          // 检查数据结构
          if (Array.isArray(response.data)) {
            console.log('数据是数组格式，直接使用')
            tableData.value = response.data
            total.value = response.data.length
          } else if (response.data && response.data.records) {
            console.log('数据是分页格式，使用records字段')
            tableData.value = response.data.records
            total.value = response.data.total || 0
          } else {
            console.log('数据格式不符合预期，使用原始数据')
            tableData.value = response.data || []
            total.value = (response.data || []).length
          }
          
          console.log('最终设置的tableData:', tableData.value)
          console.log('最终设置的total:', total.value)
        } else {
          console.error('响应状态码不是200:', response.code, response.message)
        }
      } catch (error) {
        console.error('加载选课数据失败:', error)
        ElMessage.error('加载选课数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 加载学生和课程数据
    const loadStudentsAndCourses = async () => {
      try {
        const [studentsRes, coursesRes] = await Promise.all([
          studentApi.getAllStudents(),
          courseApi.getAllCourses()
        ])
        
        if (studentsRes.code === 200) {
          students.value = studentsRes.data
        }
        if (coursesRes.code === 200) {
          courses.value = coursesRes.data
        }
      } catch (error) {
        console.error('加载学生和课程数据失败:', error)
      }
    }
    

    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      loadData()
    }
    
    // 选课
    const handleEnroll = () => {
      enrollDialogVisible.value = true
      resetEnrollForm()
    }
    
    // 录入成绩
    const handleGrade = (row) => {
      gradeForm.sno = row.sno
      gradeForm.sname = row.sname
      gradeForm.cno = row.cno
      gradeForm.cname = row.cname
      gradeForm.grade = row.grade
      gradeDialogVisible.value = true
    }
    
    // 批量录入成绩
    const handleBatchGrade = () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要录入成绩的选课记录')
        return
      }
      batchGrades.value = selectedRows.value.map(row => row.grade || 0)
      batchGradeDialogVisible.value = true
    }
    
    // 退课
    const handleDrop = (row) => {
      ElMessageBox.confirm(
        `确定要让学生 ${row.sname}(${row.sno}) 退选课程 ${row.cname}(${row.cno}) 吗？`,
        '退课确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await enrollmentApi.dropCourse(row.sno, row.cno)
          if (response.code === 200) {
            ElMessage.success('退课成功')
            loadData()
          }
        } catch (error) {
          console.error('退课失败:', error)
        }
      })
    }
    
    // 提交选课
    const handleEnrollSubmit = async () => {
      if (!enrollFormRef.value) return
      
      try {
        await enrollFormRef.value.validate()
        enrollLoading.value = true
        
        const response = await enrollmentApi.enrollCourse(enrollForm)
        if (response.code === 200) {
          ElMessage.success('选课成功')
          enrollDialogVisible.value = false
          loadData()
        }
      } catch (error) {
        console.error('选课失败:', error)
      } finally {
        enrollLoading.value = false
      }
    }
    
    // 提交成绩
    const handleGradeSubmit = async () => {
      if (!gradeFormRef.value) return
      
      try {
        await gradeFormRef.value.validate()
        gradeLoading.value = true
        
        const response = await enrollmentApi.updateGrade({
          sno: gradeForm.sno,
          cno: gradeForm.cno,
          grade: gradeForm.grade
        })
        
        if (response.code === 200) {
          ElMessage.success('成绩录入成功')
          gradeDialogVisible.value = false
          loadData()
        }
      } catch (error) {
        console.error('成绩录入失败:', error)
      } finally {
        gradeLoading.value = false
      }
    }
    
    // 批量提交成绩
    const handleBatchGradeSubmit = async () => {
      batchGradeLoading.value = true
      try {
        const promises = selectedRows.value.map((row, index) => {
          return enrollmentApi.updateGrade({
            sno: row.sno,
            cno: row.cno,
            grade: batchGrades.value[index]
          })
        })
        
        await Promise.all(promises)
        ElMessage.success('批量录入成绩成功')
        batchGradeDialogVisible.value = false
        selectedRows.value = []
        loadData()
      } catch (error) {
        console.error('批量录入成绩失败:', error)
      } finally {
        batchGradeLoading.value = false
      }
    }
    
    // 选择改变
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }
    
    // 重置选课表单
    const resetEnrollForm = () => {
      Object.keys(enrollForm).forEach(key => {
        enrollForm[key] = ''
      })
      if (enrollFormRef.value) {
        enrollFormRef.value.clearValidate()
      }
    }
    
    // 关闭选课对话框
    const handleEnrollDialogClose = () => {
      resetEnrollForm()
    }
    
    // 关闭成绩对话框
    const handleGradeDialogClose = () => {
      gradeForm.grade = null
      if (gradeFormRef.value) {
        gradeFormRef.value.clearValidate()
      }
    }
    
    // 分页大小改变
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      loadData()
    }
    
    // 当前页改变
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadData()
    }
    
    // 导出Excel
    const handleExport = () => {
      try {
        const exportData = tableData.value.map(item => ({
          '学号': item.sno,
          '学生姓名': item.sname,
          '课程号': item.cno,
          '课程名': item.cname,
          '教师': item.teacher,
          '成绩': item.grade === null || item.grade === undefined ? '未录入' : item.grade
        }))
        
        const ws = XLSX.utils.json_to_sheet(exportData)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '选课列表')
        
        const fileName = `选课列表_${new Date().toISOString().slice(0, 10)}.xlsx`
        XLSX.writeFile(wb, fileName)
        
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    onMounted(() => {
      loadData()
      loadStudentsAndCourses()
    })
    
    return {
      loading,
      enrollLoading,
      gradeLoading,
      batchGradeLoading,
      enrollDialogVisible,
      gradeDialogVisible,
      batchGradeDialogVisible,
      enrollFormRef,
      gradeFormRef,
      searchForm,
      enrollForm,
      gradeForm,
      tableData,
      currentPage,
      pageSize,
      total,
      students,
      courses,
      selectedRows,
      batchGrades,
      enrollRules,
      gradeRules,
      handleSearch,
      handleReset,
      handleEnroll,
      handleGrade,
      handleBatchGrade,
      handleDrop,
      handleEnrollSubmit,
      handleGradeSubmit,
      handleBatchGradeSubmit,
      handleSelectionChange,
      handleEnrollDialogClose,
      handleGradeDialogClose,
      handleSizeChange,
      handleCurrentChange,
      handleExport
    }
  }
}
</script>

<style scoped>
.enrollments-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.table-card {
  background: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.no-selection {
  text-align: center;
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: left !important;
}

:deep(.el-table td) {
  text-align: left !important;
}

:deep(.el-table .cell) {
  text-align: left !important;
}
</style>